package com.tl.commonlibrary.tool;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;


public class DeviceUtil {
    private static final String DEVICE_ID = "dexyppqls";

    public static int dp_to_px(int dp, Context context) {
        return (int) (dp * context.getResources().getDisplayMetrics().density + 0.5f);
    }

    public static int px_to_dp(int px, Context context) {
        return (int) (px / context.getResources().getDisplayMetrics().density + 0.5f);
    }

    public static int sp_to_px(int sp, Context context) {
        return (int) (sp * context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
    }

    public static int px_to_sp(int px, Context context) {
        return (int) (px / context.getResources().getDisplayMetrics().scaledDensity + 0.5f);
    }

    public static DisplayMetrics getScreen(Activity context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    public static void dial(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    //获取版本号
    public static String getVersionName(Context context) {
        String versionName = "unkown";
        if (context != null) {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = null;
            try {
                packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return versionName;
    }

    //获取版本号
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        if (context != null) {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packInfo = null;
            try {
                packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionCode = packInfo.versionCode;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return versionCode;
    }

    /**
     * 获取设备型号
     *
     * @return 设备型号
     */
    public static String getModel() {
        String model = Build.MODEL;
        if (model != null) {
            model = model.trim().replaceAll("\\s*", "");
        } else {
            model = "";
        }
        return model;
    }

//    public static String getDeviceId(Context context) {
//        PrefUtil preferenceTool = new PrefUtil(context);
//        String deviceId = preferenceTool.getString(DEVICE_ID);//配置文件中获取,卸载或者清除数据将清空
//        if (!TextUtils.isEmpty(deviceId)) {
//            if (APPGlobal.DEBUGGABLE) {
//                System.out.println("did(from preference)=" + deviceId);
//            }
//            return deviceId;
//        }
//        deviceId = FileCacheTool.load(DEVICE_ID);//sd默认缓存文件获取，卸载将清空
//        if (!TextUtils.isEmpty(deviceId)) {
//
//            if (APPGlobal.DEBUGGABLE) {
//                System.out.println("did(from cache)=" + deviceId);
//            }
//            return deviceId;
//        }
//        deviceId = FileCacheTool.load(FileCacheTool.getForbiddenCachePath(), DEVICE_ID);//sd指定位置获取，卸载不会清空
//        if (!TextUtils.isEmpty(deviceId)) {
//            if (APPGlobal.DEBUGGABLE) {
//                System.out.println("did(from cache forbidden)=" + deviceId);
//            }
//            return deviceId;
//        }
//
//        //从以上缓存中都没有拿到DeviceId，去实际获取该值，并保存下来
//        StringBuffer sBuffer = new StringBuffer();
//        deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();//1.1.1版本之前的deviceId
//        if (TextUtils.isEmpty(deviceId)) {
//            //有可能deviceId为空，1.1.1之前的bug
//            String cupId = getCPUSerial();
//            if (TextUtils.isEmpty(cupId) || cupId.equals("0000000000000000")) {
//                cupId = String.valueOf(UUID.randomUUID());
//            }
//            String wifiID = getWIFIMACID(context);
//            deviceId = sBuffer.append(cupId).append(wifiID).toString();
//            deviceId = MD5Util.getMD5(deviceId);
//        }
//        if (!TextUtils.isEmpty(deviceId)) {
//            preferenceTool.putString(DEVICE_ID, deviceId);//保存至配置文件
//            FileCacheTool.save(DEVICE_ID, deviceId);//保存至默认缓存
//            FileCacheTool.save(FileCacheTool.getForbiddenCachePath(), DEVICE_ID, deviceId);//保存至指定缓存
//        }
//        if (APPGlobal.DEBUGGABLE) {
//            System.out.println("did(from calculation)=" + deviceId);
//        }
//        return deviceId;
//    }

    /**
     * @return
     * @Title: getCPUSerial
     * 获取CUP型号
     */
//    public static String getCPUSerial() {
//        String str = "", strCPU = "", cpuAddress = "0000000000000000";
//        try {
//            // 读取CPU信息
//            Process pp = Runtime.getRuntime().exec("cat/proc/cpuinfo");
//            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
//            LineNumberReader input = new LineNumberReader(ir);
//            // 查找CPU序列号
//            for (int i = 1; i < 100; i++) {
//                str = input.readLine();
//                if (str != null) {
//                    // 查找到序列号所在行
//                    if (str.indexOf("Serial") > -1) {
//                        // 提取序列号
//                        strCPU = str.substring(str.indexOf(":") + 1, str.length());
//                        // 去空格
//                        cpuAddress = strCPU.trim();
//                        break;
//                    }
//                } else {
//                    // 文件结尾
//                    break;
//                }
//            }
//        } catch (IOException ex) {
//            // 赋予默认值
//            if (APPGlobal.DEBUGGABLE) {
//                ex.printStackTrace();
//            }
//        }
//        return cpuAddress;
//    }

    /**
     * @param context
     * @return
     * @Title: getWIFIMACID
     * 获取MAC地址
     */
    public static String getWIFIMACID(Context context) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wm.getConnectionInfo().getMacAddress();

    }

    public static boolean clipboardSet(Context context, String text) {
        if (context == null || TextUtils.isEmpty(text)) {
            return false;
        }
        if (Build.VERSION.SDK_INT < 11) {
            android.text.ClipboardManager tClipboardManager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            if (tClipboardManager != null) {
                tClipboardManager.setText(text);
                return true;
            }
        } else {
            ClipboardManager cClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            if (cClipboardManager != null) {
                cClipboardManager.setPrimaryClip(ClipData.newPlainText(null, text));
                return true;
            }
        }
        return false;
    }

    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }

    public static void goMarket(Context context) {
        try {
            Uri uri = Uri.parse("market://details?id=" + context.getPackageName());
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            UIUtils.showToast("您的手机没有安装Android应用市场");
            e.printStackTrace();
        }
    }

    /**
     * @param context
     * @return
     */
    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {

                    return true;
                } else {

                    return false;
                }
            }
        }
        return false;
    }

    public static int getSdkVersionCode() {
        int version = 0;
        try {
            version = Integer.valueOf(Build.VERSION.SDK_INT);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String getSdkVersionName() {
        return Build.VERSION.RELEASE;
    }

    @SuppressLint("NewApi")
    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
//        if (Build.VERSION.SDK_INT >= 23) {
//            if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
//                result = true;
//            }
//        } else {
        PackageManager pm = context.getPackageManager();
        if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
            result = true;
        }
//        }
        return result;
    }

    public static String getDeviceInfo(Context context) {
        org.json.JSONObject json = new org.json.JSONObject();
        try {
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                try {
                    fstream = new FileReader("/sys/class/net/eth0/address");
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                }
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        lp.dimAmount = 1 - bgAlpha;
        context.getWindow().setAttributes(lp);
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }
}
